package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.entity.Food;
import com.neuedu.mapper.FoodMapper;
import com.neuedu.service.FileUploadService;
import com.neuedu.service.FoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.vo.ResultJson;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 * 食品表 服务实现类
 * </p>
 *
 * @author wangyu
 * @since 2025-10-21
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {
    @Resource
    FileUploadService fileUploadService;
    @Override
    public IPage<Food> list(Integer pageNo, Integer pageSize, String name, String type) {
        QueryWrapper<Food> wrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(name)) {
            wrapper.like("name", name);
        }
        if(StringUtils.isNoneBlank(type)) {
            wrapper.like("type", type);
        }
        wrapper.orderByDesc("id");
        return this.page(new Page<>(pageNo, pageSize), wrapper);
    }

    @Override
    public boolean add(Food food, MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String img = fileUploadService.upload(file, "images");
        food.setImg(img);
        return this.save(food);
    }

    @Override
    public boolean update(Food food, MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (null != file) {
            String img = fileUploadService.upload(file, "images");
            food.setImg(img);
        }
        return this.updateById(food);
    }

    @Override
    public List<Food> getList() {
        QueryWrapper<Food> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id")
                .select("id, name");
        return this.list(wrapper);
    }

}
